<template>
  <MySplitPanes>
    <pane size="15" min-size="15" max-size="15">
      <div class="my-flex-column w100 h100">
        <production-line-menu @node-click="onProductionLineNodeClick" select-first-node></production-line-menu>
      </div>
    </pane>
    <pane>
      <div class="my-flex-column w100 h100">
        <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
          <el-form :inline="true" label-width="auto" @submit.stop.prevent>
            <el-form-item>
              <my-select-input v-model="state.pageInput.dynamicFilter" :filters="state.filters" @search="onQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
              <el-button type="primary" icon="ele-Search" @click="onFilter"> 高级查询 </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="my-fill mt8" shadow="never">
          <div class="my-tools-box mb8 my-flex my-flex-between">
            <div>
              <el-button v-auth="'api:industry:work-station:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增
              </el-button>
            </div>
            <div>
              <el-tooltip effect="dark" :content="state.showTableOrCard ? '卡片' : '列表'" placement="top">
                <el-button :icon="state.showTableOrCard ? 'ele-Grid' : 'ele-List'" circle
                  @click="state.showTableOrCard = !state.showTableOrCard" />
              </el-tooltip>
              <el-tooltip effect="dark" :content="state.showQuery ? '隐藏查询' : '显示查询'" placement="top">
                <el-button :icon="state.showQuery ? 'ele-ArrowUp' : 'ele-ArrowDown'" circle
                  @click="state.showQuery = !state.showQuery" />
              </el-tooltip>
            </div>
          </div>
          <div v-if="!state.showTableOrCard" style="height: 100%;">
            <el-row :gutter="10" type="flex">
              <el-col v-for="item in state.workStationListData" :key="item.id" :span="6">
                <el-card shadow="always" style="margin-bottom: 10px;">
                  <template #header>
                    <div>
                      <el-row :gutter="10" justify="space-between">
                        <el-col :span="6">
                          <h1>
                            <el-tag>{{ item.stationCode }}</el-tag>
                          </h1>
                        </el-col>
                        <el-col :span="6">
                          <div>
                            <my-dropdown-more icon-only
                              v-auths="['api:industry:work-station:soft-delete', 'api:industry:work-station:update']">
                              <template #dropdown>
                                <el-dropdown-menu>
                                  <el-dropdown-item v-if="auth('api:industry:work-station:update')"
                                    @click="onEdit(item)">编辑</el-dropdown-item>
                                  <el-dropdown-item v-if="auth('api:industry:work-station:soft-delete')"
                                    @click="onDelete(item)">删除</el-dropdown-item>
                                </el-dropdown-menu>
                              </template>
                            </my-dropdown-more>
                          </div>
                        </el-col>
                      </el-row>
                    </div>
                  </template>
                  <el-row :gutter="10" justify="space-between">
                    <el-col :span="12">
                      名称:
                    </el-col>
                    <el-col :span="12">
                      <div style="height: 10px;text-overflow: ellipsis;">
                        {{ item.stationName }}
                      </div>
                    </el-col>
                  </el-row>
                  <template #footer>
                    <el-row :gutter="10" justify="space-between">
                      <el-col :span="6">
                        <el-button v-auth="'api:industry:work-station:set-comm-state'" icon="ele-Odometer"
                          color="#67C23A" @Click="onSetCommState(item, 1)" />
                      </el-col>
                      <el-col :span="6">
                        <el-button v-auth="'api:industry:work-station:set-comm-state'" icon="ele-SwitchButton"
                          color="#F56C6C" @Click="onSetCommState(item, 2)" />
                      </el-col>
                    </el-row>
                  </template>
                </el-card>
              </el-col>
            </el-row>
          </div>
          <el-table v-if="state.showTableOrCard" ref="tableRef" v-loading="state.loading"
            :data="state.workStationListData" row-key="id" @sort-change="onSortChange" border>
            <el-table-column type="selection" />
            <el-table-column prop="stationCode" label="工站代号" width="100" show-overflow-tooltip />
            <el-table-column prop="stationName" label="工站名称" width="100" show-overflow-tooltip />
            <el-table-column prop="stationType" label="工站类型" width="100" show-overflow-tooltip />
            <el-table-column label="产线名称" width="100" show-overflow-tooltip align="center">
              <template #default="{ row }">
                <el-tag>{{ row.lineName }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="80" align="center" sortable="custom" show-overflow-tooltip />
            <el-table-column label="状态" width="80" align="center" fixed="right">
              <template #default="{ row }">
                <el-switch v-if="auth('api:industry:work-station:set-enable')" v-model="row.enabled"
                  :loading="row.loading" :active-value='true' :inactive-value='false' inline-prompt active-text="开启"
                  inactive-text="关闭" :before-change="() => onSetEnable(row)" />
                <template v-else>
                  <el-tag type="success" v-if="row.enabled">启用</el-tag>
                  <el-tag type="danger" v-else>禁用</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="equipmentList" label="设备清单" width="140" show-overflow-tooltip />
            <el-table-column prop="capacity" label="小时件" width="85" show-overflow-tooltip />
            <el-table-column prop="cycleTime" label="循环时间" width="90" show-overflow-tooltip />
            <el-table-column prop="shiftCount" label="班次数量" width="85" show-overflow-tooltip />
            <el-table-column prop="workHours" label="工作小时数" width="160" show-overflow-tooltip />
            <el-table-column prop="location" label="工站位置" width="160" show-overflow-tooltip />
            <el-table-column prop="startTime" label="启用时间" :formatter="formatterTime" width="160"
              show-overflow-tooltip />
            <el-table-column prop="endTime" label="停用时间" :formatter="formatterTime" width="160" show-overflow-tooltip />
            <el-table-column prop="remarks" label="备注" width="100" show-overflow-tooltip />
            <el-table-column label="操作" width="140" header-align="center" align="center" fixed="right">
              <template #default="{ row }">
                <el-button v-auth="'api:industry:work-station:update'" icon="ele-EditPen" size="small" text
                  type="primary" @click="onEdit(row)">编辑</el-button>
                <my-dropdown-more v-auths="['api:industry:work-station:soft-delete']">
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-if="auth('api:industry:work-station:soft-delete')"
                        @click="onDelete(row)">删除工位</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </my-dropdown-more>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <div class="my-flex my-flex-end" style="margin-top: 10px">
          <el-pagination v-model:currentPage="state.pageInput.currentPage" v-model:page-size="state.pageInput.pageSize"
            :total="state.total" :page-sizes="[10, 20, 50, 100]" small background @size-change="onSizeChange"
            @current-change="onCurrentChange" layout="total, sizes, prev, pager, next, jumper" />
        </div>
      </div>
      <work-station-form ref="workStationFormRef" :title="state.workStationFormTitle"></work-station-form>
      <MyFilterDialog ref="myFilterDialogRef" :fields="state.filters" @sure="onFilterSure"></MyFilterDialog>
    </pane>
  </MySplitPanes>
</template>
<script lang="ts" setup name="industry/workStation">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent, computed } from 'vue'
import { PageInputWorkStationGetPageInput, WorkStationGetPageOutput, WorkStationGetOutput, ProductionLineGetOutput, SortInput, WorkStationGetPageInput } from '/@/api/industry/data-contracts'
import { WorkStationApi } from '/@/api/industry/WorkStation'
import { Pane } from 'splitpanes'
import dayjs from 'dayjs'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import { ElTable } from 'element-plus'
import { reject } from 'lodash-es'

const WorkStationForm = defineAsyncComponent((() => import('./compoents/work-station-form.vue')))
const MySplitPanes = defineAsyncComponent(() => import('/@/components/my-layout/split-panes.vue'))
const ProductionLineMenu = defineAsyncComponent(() => import('/@/views/industry/production-line/compoents/production-line-menu.vue'))
const MySelectInput = defineAsyncComponent(() => import('/@/components/my-select-input/index.vue'))
const MyDropdownMore = defineAsyncComponent(() => import('/@/components/my-dropdown-more/index.vue'))
const MyFilterDialog = defineAsyncComponent(() => import('/@/components/my-filter/dialog.vue'))

const { proxy } = getCurrentInstance() as any
const getSortList = (data: { prop: string; order: any }) => {
  return [
    {
      propName: data.prop,
      order: data.order === 'ascending' ? 0 : data.order === 'descending' ? 1 : undefined,
    },
  ] as [SortInput]
}
const defalutSort = { prop: 'sort', order: 'ascending' }
const workStationFormRef = ref()
const myFilterDialogRef = ref();
const state = reactive({
  loading: false,
  showQuery: true,
  showTableOrCard: true,
  workStationFormTitle: '',
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
    sortList: getSortList(defalutSort),
    filter: {
      lineId: 0,
      lineName: ''
    } as WorkStationGetPageInput,
    dynamicFilter: {},
  } as PageInputWorkStationGetPageInput,
  workStationListData: [] as Array<WorkStationGetPageOutput>,
  filters: [
    {
      field: 'stationCode',
      operator: 'Contains',
      description: '工位代号',
      componentName: 'el-input',
      defaultSelect: true,
    },
    {
      field: 'stationName',
      operator: 'Contains',
      description: '工位名称',
      componentName: 'el-input',
    }
  ] as Array<DynamicFilterInfo>,
})
onMounted(async () => {
  eventBus.off('refreshWorkStation')
  eventBus.on('refreshWorkStation', async () => {
    onQuery()
  })
})
onBeforeMount(() => {
  eventBus.off('refreshWorkStation')
})
const formatterTime = (row: any, column: any, cellValue: any) => {
  return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
}

const onSortChange = (data: { column: any; prop: string; order: any }) => {
  state.pageInput.sortList = getSortList(data)
  onQuery()
}
//查询分页
const onQuery = async () => {
  state.loading = true
  const res = await new WorkStationApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })

  state.workStationListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}
//高级查询
const onFilter = () => {
  myFilterDialogRef.value.open()
}

const onFilterSure = (dynamicFilter: any) => {
  state.pageInput.dynamicFilter = dynamicFilter
  onQuery()
}

//新增
const onAdd = () => {
  state.workStationFormTitle = `新增【${state.pageInput.filter?.lineName}】工站信息`
  workStationFormRef.value.open({ lineId: state.pageInput.filter?.lineId })
}

//修改
const onEdit = (row: WorkStationGetOutput) => {
  state.workStationFormTitle = `编辑【${state.pageInput.filter?.lineName}】工站【${row.stationName}】信息`
  workStationFormRef.value.open(row)
}

//删除
const onDelete = (row: WorkStationGetOutput) => {
  proxy.$modal
    .confirmDelete(`确定要删除工站代号为【${row.stationCode}】?`)
    .then(async () => {
      await new WorkStationApi().softDelete({ id: row.id }, { loading: true, showSuccessMessage: true })
      onQuery()
    })
    .catch(() => { })
}
//启用或禁用
const onSetEnable = (row: WorkStationGetOutput & { loading: boolean }) => {
  return new Promise((resolve, reject) => {
    proxy.$modal
      .confirm(`确定要${row.enabled ? '禁用' : '启用'}工位代号为：【${row.stationCode}】?`)
      .then(async () => {
        row.loading = true
        const res = await new WorkStationApi()
          .setEnable({ stationId: row.id, enabled: !row.enabled }, { showSuccessMessage: true })
          .catch(() => {
            reject(new Error('Error'))
          })
          .finally(() => {
            row.loading = false
          })
        if (res && res.success) {
          resolve(true)
        } else {
          reject(new Error('Cancel'))
        }
      })
      .catch(() => {
        reject(new Error('Cancel'))
      })
  })
}

const onSetCommState = (item: WorkStationGetOutput, state: any) => {
  return new Promise((resolve, reject) => {
    proxy.$modal
      .confirm(`确定要改变工站代号为【${item.stationCode}】的设备通讯？`)
      .then(async () => {
        const res = new WorkStationApi()
          .setCommState({ workStationId: item.id, state: state }, { showSuccessMessage: true })
          .catch(() => {
            reject(new Error('Error'))
          })
      })
  })
}

const onSizeChange = (val: number) => {
  state.pageInput.currentPage = 1
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}
const onProductionLineNodeClick = (node: ProductionLineGetOutput | null) => {
  if (state.pageInput.filter) {
    state.pageInput.filter.lineId = node?.id
    state.pageInput.filter.lineName = node?.lineName
  }
  onQuery()
}
</script>
<style scoped lang="scss">
.el-card .el-card__footer {
  padding: 1px;
}
</style>
